package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author Jetwang
 * @version 1.0
 * @date 2022/4/12 10:50
 * CommonController 公共控制器  负责文件的上传和下载
 */
@RequestMapping("common")
@Slf4j
@RestController
public class CommonController {
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {
        // file时一个临时文件，需要转存
        String originalFilename = file.getOriginalFilename();
        log.info("文件名: {}", originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        // 使用UUID生成文件名，防止文件名覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        // 创建一个目录对象
        File dir = new File(Constant.BASE_PATH);
        // 目录不存在
        if (!dir.exists()) {
            // 目录不存在，创建目录
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(Constant.BASE_PATH + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) {
        FileInputStream is = null;
        OutputStream os = null;
        try {
            // 输入流读取文件内容
            is = new FileInputStream(new File(Constant.BASE_PATH + name));
            os = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                // 输出流响应图片到浏览器
                os.write(bytes, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
